import React, {useCallback} from 'react';
import {Button, Field, Table, Card, Message} from '@alifd/next';
import {useFusionTable, useSetState} from 'ahooks';

import {request} from 'ice';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import {ActionType, OperaitionProps} from './Operation';

import styles from './index.module.scss';

const getTableData = (
  {current, pageSize}: { current: number; pageSize: number },
  formData: { status: 'normal' | 'empty' | 'exception' }
): Promise<any> => {
  if (!formData.status || formData.status === 'normal') {
    const data = request({
      url: '/v1/stall/dictionary',
      method: 'get',
    });
    return data.then(res => {
      return {
        list: res.data,
      }
    })
  }
  if (formData.status === 'empty') {
    return Promise.resolve([]);
  }
  if (formData.status === 'exception') {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('data exception'));
      }, 1000);
    });
  }

  return Promise.resolve([]);
};

// eslint-disable-next-line @typescript-eslint/interface-name-prefix
interface ColumnWidth {
  name: number;
  email: number;
  phone: number;
  gender: number;
  operation: number;
}

// eslint-disable-next-line @typescript-eslint/interface-name-prefix
interface DialogState {
  columnWidth: ColumnWidth;
  optCol: any;
  actionType: ActionType;
  actionVisible: boolean;
}

const defaultColumnWidth: ColumnWidth = {
  name: 140,
  email: 500,
  phone: 500,
  gender: 140,
  operation: 150,
};

const DialogTable: React.FC = () => {
  const [state, setState] = useSetState<DialogState>({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const {actionVisible, columnWidth, optCol} = state;
  const field = Field.useField([]);
  // eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars
  const {tableProps, search, error, refresh} = useFusionTable(getTableData, {
    field,
  });

  const {reset} = search;

  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    setState({columnWidth: newWidth});
  };

  const operationCallback = useCallback(({actionType, dataSource}: OperaitionProps): void => {
    setState({
      actionType,
      optCol: dataSource,
      actionVisible: true,
    });
  }, [setState]);

  const handleCancel = useCallback((): void => {
    setState({actionVisible: false});
  }, [setState]);

  const handleOk = useCallback((): void => {
    // eslint-disable-next-line no-shadow,no-unused-vars
    const {actionType} = state;
    if (actionType === 'preview') {
      handleCancel();
      return;
    }
    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);


  const cellOperation = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return (
      <div>
        <Button
          text
          type="primary"
          onClick={() => operationCallback({actionType: 'edit', dataSource: record})}
        >
          编辑
        </Button>
      </div>
    );
  };

  return (
    <div className={styles.DialogTable}>
      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh}/> : <EmptyBlock/>}
            primaryKey="email"
          >
            <Table.Column title="摊位ID" dataIndex="id" resizable width={columnWidth.name}/>
            <Table.Column title="摊位名称" dataIndex="name" resizable width={columnWidth.name}/>

            <Table.Column title="小摊升中摊声望" dataIndex="minToMiddle" resizable width={columnWidth.name}/>
            <Table.Column title="中摊升大摊声望" dataIndex="middleToLager" resizable width={columnWidth.name}/>

            <Table.Column title="小摊需要人数" dataIndex="minNeedPeople" resizable width={columnWidth.name}/>
            <Table.Column title="中摊需要人数" dataIndex="middleNeedPeople" resizable width={columnWidth.name}/>
            <Table.Column title="大摊需要人数" dataIndex="largeNeedPeople" resizable width={columnWidth.name}/>

            <Table.Column title="小摊需要声望" dataIndex="minNeedPrestige" resizable width={columnWidth.name}/>
            <Table.Column title="中摊需要声望" dataIndex="middleNeedPrestige" resizable width={columnWidth.name}/>
            <Table.Column title="大摊需要声望" dataIndex="largeNeedPrestige" resizable width={columnWidth.name}/>

            <Table.Column title="小摊收获时间(分)" dataIndex="minInvestmentCycle" resizable width={columnWidth.name}/>
            <Table.Column title="中摊收获时间(分)" dataIndex="middleInvestmentCycle" resizable width={columnWidth.name}/>
            <Table.Column title="大摊收获时间(分)" dataIndex="maxInvestmentCycle" resizable width={columnWidth.name}/>

            <Table.Column title="小摊收获" dataIndex="minReward" resizable width={columnWidth.name}/>
            <Table.Column title="中摊收获" dataIndex="middleReward" resizable width={columnWidth.name}/>
            <Table.Column title="大摊收获" dataIndex="largeReward" resizable width={columnWidth.name}/>

            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation}/>
          </Table>
          {/* <Pagination pageSizeList={[10,20]} pageSizeSelector="filter"  style={{ marginTop: 16, textAlign: 'right' }} totalRender={total => <>共 <Button text type="primary">{total}</Button> 个记录</>}  {...paginationProps} /> */}
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
}

export default DialogTable;
